<?php
require_once __DIR__ . '/../common/function.php';
checkLogin();

$action = $_REQUEST['action'] ?? '';
global $pdo;

switch ($action) {
    // 获取用户列表
    case 'list':
        try {
            $stmt = $pdo->query("SELECT id, username, nickname, email, role, status, create_time FROM users ORDER BY id DESC");
            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
            success($users, '获取成功');
        } catch (PDOException $e) {
            error('获取失败：' . $e->getMessage());
        }
        break;

    // 新增用户
    case 'add':
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $nickname = trim($_POST['nickname'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = intval($_POST['role'] ?? 0);
        $status = intval($_POST['status'] ?? 1);

        // 验证参数
        if (empty($username) || empty($password)) {
            error('用户名和密码不能为空');
        }
        if (strlen($password) < 6) {
            error('密码长度不能少于6位');
        }

        try {
            // 检查用户名是否已存在
            $checkStmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $checkStmt->execute([$username]);
            if ($checkStmt->fetch()) {
                error('用户名已存在');
            }

            // 插入新用户（密码md5加密）
            $stmt = $pdo->prepare("INSERT INTO users (username, user_pwd, nickname, email, role, status) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$username, md5($password), $nickname, $email, $role, $status]);
            success([], '新增成功');
        } catch (PDOException $e) {
            error('新增失败：' . $e->getMessage());
        }
        break;

    // 编辑用户
    case 'edit':
        $id = intval($_POST['id'] ?? 0);
        $nickname = trim($_POST['nickname'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = intval($_POST['role'] ?? 0);
        $status = intval($_POST['status'] ?? 1);
        $password = trim($_POST['password'] ?? ''); // 密码可选

        if ($id <= 0) {
            error('无效的用户ID');
        }

        try {
            // 检查用户是否存在
            $checkStmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
            $checkStmt->execute([$id]);
            if (!$checkStmt->fetch()) {
                error('用户不存在');
            }

            // 构建更新字段（密码为空则不更新）
            $updateFields = [
                'nickname' => $nickname,
                'email' => $email,
                'role' => $role,
                'status' => $status
            ];
            $sql = "UPDATE users SET nickname = ?, email = ?, role = ?, status = ?";
            $params = [$nickname, $email, $role, $status];

            // 若填写了密码，则添加更新密码逻辑
            if (!empty($password)) {
                if (strlen($password) < 6) {
                    error('密码长度不能少于6位');
                }
                $sql .= ", user_pwd = ?";
                $params[] = md5($password);
            }
            $sql .= " WHERE id = ?";
            $params[] = $id;

            // 执行更新
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            success([], '更新成功');
        } catch (PDOException $e) {
            error('更新失败：' . $e->getMessage());
        }
        break;

    // 删除用户
    case 'delete':
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            error('无效的用户ID');
        }
        // 禁止删除当前登录用户
        if ($id == $_SESSION['user_id']) {
            error('不能删除当前登录用户');
        }

        try {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$id]);
            success([], '删除成功');
        } catch (PDOException $e) {
            error('删除失败：' . $e->getMessage());
        }
        break;

    default:
        error('无效操作');
}